<template>
  <div class="global-container" v-loading="loading">
    <div class="main">
      <template v-if="serviceType === '2'">
        <CostSteps v-if="certType === '1' && !!formData.id" :bussType="bussType" :applyId="id" :formData="formData" @loading="handleLoading"/>
        <SafeSteps v-if="certType === '3' && !!formData.id" :bussType="bussType" :applyId="id" :formData="formData" @loading="handleLoading" />
        <CompanySteps v-if="certType === '2' && !!formData.applyId" :bussType="bussType" :applyId="id" :formData="formData" @loading="handleLoading" />
      </template>
      <template v-else>
        <template v-if="isCompanyBussType">
          <CompanySteps2 v-if="tabsActive == 1" :id="userId" disabled />
          <CompanySteps3
              ref="CompanySteps3"
              v-show="tabsActive == 2"
              :id="id"
              :userId="userId"
              :bussType="bussType"
              :disabled="disabled || type !== 'correction'"
              @loading="handleLoading"
          />
          <CompanySteps4
              v-if="tabsActive == 3"
              :id="id"
              :userId="userId"
              :bussType="bussType"
              :disabled="type !== 'correction'"
          />
        </template>
        <template v-else>
          <PersonalSteps2 v-if="tabsActive == 1" :certType="certType" :id="userId" disabled />
          <PersonalSteps3
              ref="PersonalSteps3"
              v-show="tabsActive == 2"
              :id="id"
              :userId="userId"
              :bussType="bussType"
              :disabled="disabled || type !== 'correction'"
              :certType="certType"
              @loading="handleLoading"
          />
          <PersonalSteps4
              v-if="tabsActive == 3"
              :id="id"
              :userId="userId"
              :bussType="bussType"
              :disabled="type !== 'correction'"
          />
        </template>
      </template>
      <ProcessOpinion
        ref="ProcessOpinion"
        v-if="tabsActive == 4"
        :formData="formData"
        :id="id"
        :disabled="
          type === 'correction' ||
          type === 'process' ||
          disabled == 'true' ||
          disabled === true
        "
        @loading="handleLoading"
      />
      <ProcessReview
        ref="ProcessReview"
        v-if="tabsActive == 5"
        :formData="formData"
        :id="id"
        :disabled="disabled == 'true' || disabled === true"
      />
    </div>
    <div class="footer">
      <el-button
        type="primary"
        class="btn"
        v-if="submittable"
        @click="submit"
        >提交</el-button
      >
      <el-button
        type="primary"
        class="btn"
        v-if="+tabsActive == 3 && type === 'correction'"
        @click="correction"
        >提交补正</el-button
      >
      <el-button class="btn" @click="backClick()">返回</el-button>
    </div>
  </div>
</template>

<script>
import PersonalSteps2 from '@/views/apply-online/personal/need-apply/components/Steps2.vue';
import PersonalSteps3 from '@/views/apply-online/personal/need-apply/components/Steps3.vue';
import PersonalSteps4 from '@/views/apply-online/personal/need-apply/components/Steps4.vue';
import CompanySteps2 from '@/views/apply-online/company/need-apply/components/Steps2.vue';
import CompanySteps3 from '@/views/apply-online/company/need-apply/components/Steps3.vue';
import CompanySteps4 from '@/views/apply-online/company/need-apply/components/Steps4.vue';
import CostSteps from '@/views/process/components/steps/CostSteps.vue';
import SafeSteps from '@/views/process/components/steps/SafeSteps.vue';
import CompanySteps from '@/views/process/components/steps/CompanySteps.vue';
import ProcessOpinion from './ProcessOpinion.vue';
import ProcessReview from './ProcessReview.vue';
import businessApi from '@/api/business';
import { decrypt } from '@/utils/sms4util';

export default {
  props: {
    type: {
      default: 'accept',
    },
    id: {
      type: String,
    },
    bussType: {
      default: '1',
    },
    userId: {
      type: String,
    },
    serviceType: {
      type: String,
    },
    disabled: {
      default: false,
    },
    routePathName: {
      type: String,
    },
    routeCurrentParams: {
      default: () => {
        return {};
      },
    },
  },
  components: {
    PersonalSteps2,
    PersonalSteps3,
    PersonalSteps4,
    CompanySteps2,
    CompanySteps3,
    CompanySteps4,
    ProcessOpinion,
    ProcessReview,
    CompanySteps, CostSteps, SafeSteps
  },
  data() {
    return {
      formData: {
        slFile: {},
        scFile: {},
      },
      loading: false,
    };
  },
  computed: {
    tabsActive() {
      return this.$store.state.tabs.tabsActive;
    },
    tabsOptions() {
      const arr = [
        { label: '申请人信息', value: '1' },
        { label: '申请表', value: '2' },
        { label: '材料清单', value: '3' },
        { label: '受理意见', value: '4' },
        { label: '审查意见', value: '5' },
      ];
      if (this.serviceType === '2') {
        if (this.type === 'accept' || this.type === 'correction') {
          return arr.slice(1, 4);
        } else if (this.type === 'unhandled') {
          return arr.slice(1, 3);
        } else {
          return arr.slice(1);
        }
      } else {
        if (this.type === 'accept' || this.type === 'correction') {
          return arr.slice(0, 4);
        } else if (this.type === 'unhandled') {
          return arr.slice(0, 3);
        } else {
          return arr;
        }
      }
    },
    isCompanyBussType() {
      return this.bussType == 5 || this.bussType == 6 ||
          this.bussType == 7 || this.bussType == 8 || this.bussType == 9;
    },
    certType() {
      return businessApi.getCertType(this.bussType);
    },
    submittable() {
      if (this.serviceType === '2') {
        return +this.tabsActive > this.tabsOptions.length &&
            !this.disabled &&
            this.type != 'correction'
      } else {
        return +this.tabsActive == this.tabsOptions.length &&
            !this.disabled &&
            this.type != 'correction';
      }
    },
    attachments() {
      return this.$store.state.user.attachments;
    }
  },
  destroyed() {
    this.$store.commit('tabs/setTabsActive', '');
    this.$store.commit('tabs/setTabsOptions', []);
  },
  mounted() {
    if (this.serviceType === '2') {
      this.$store.commit('tabs/setTabsActive', '2');
    } else {
      this.$store.commit('tabs/setTabsActive', '1');
    }
    this.$store.commit('tabs/setTabsOptions', this.tabsOptions);
    this.initData();
  },
  methods: {
    backClick() {
      if (this.routePathName) {
        this.$router.push({
          name: this.routePathName,
          query: {
            bussType: this.routeCurrentParams.bussType,
          },
          params: this.routeCurrentParams,
        });
      } else {
        this.$router.back();
      }
    },
    async initData() {
      this.loading = true;
      let params = {
        id: this.id,
        type: this.bussType,
      };
      // 获取申请信息
      const res = await businessApi.getStepsInfo(params);
      this.formData = {
        ...res,
        paperCode: res.paperCode ? decrypt(res.paperCode) : '',
        creditCode: res.creditCode ? decrypt(res.creditCode) : '',
        czztdm: res.czztdm ? decrypt(res.czztdm) : '',
        conNum: res.conNum ? decrypt(res.conNum) : '',
        phone: res.phone ? decrypt(res.phone) : (this.needDecryptPhone(res) ? decrypt(res.createBy) : ''),
        unitTel: res.unitTel ? decrypt(res.unitTel) : '',
        sqrTel: res.sqrTel ? decrypt(res.sqrTel) : '',
        jbrTel: res.jbrTel ? decrypt(res.jbrTel) : '',
      };
      if (!this.disabled) {
        // 受理/审查
        if (this.type == 'accept') {
          this.formData.slPer = this.$store.state.user.userInfo.realname;
          this.formData.slTime = this.$dayjs().format('YYYY-MM-DD');
          this.formData.slFile = this.formData.slFile || {};
        } else if (this.type == 'correction') {
          this.formData.acceptResult = '9';
        } else {
          this.formData.scPer = this.$store.state.user.userInfo.realname;
          this.formData.scTime = this.$dayjs().format('YYYY-MM-DD');
          this.formData.scFile = {};
          this.formData.acceptResult = this.formData.status;
        }
      } else {
        // 处理结果
        if (+this.formData.status > 2) {
          this.formData.acceptResult = +this.formData.status == 9 ? '9' : '3';
          this.formData.processResult = this.formData.status;
        } else {
          this.formData.acceptResult = this.formData.status;
        }
      }
      this.loading = false;
    },
    async submit() {
      this.loading = true;
      this.formData.id = this.formData.applyId;
      // 提交受理/审核结果
      if (this.tabsActive == 4) {
        try {
          await this.$refs['ProcessOpinion'].checkValidate();
          let status = this.formData.acceptResult;
          this.formData.slFile = null;
          if (this.formData.serviceType === '2') {
            const stuffList = this.formData.stuffInfoList || [];
            if (stuffList && stuffList.length > 0) {
              this.formData = {
                ...this.formData,
                stuffInfoList: this.attachments.filter(item => stuffList.includes(item.stuffUniId))
              }
            }
            await businessApi.newApplyApprove(status, this.formData).finally(()=>{
              this.loading = false;
            });
          } else {
            await businessApi.applyApprove(status, this.formData).finally(()=>{
              this.loading = false;
            });
          }
          this.$message.success('提交成功');
          this.$router.back();
        } catch (error) {
          this.loading = false;
          console.log(error);
        }
      } else {
        try {
          await this.$refs['ProcessReview'].checkValidate();
          let status = this.formData.processResult;
          if (this.formData.serviceType === '2') {
            await businessApi.newApplyApprove(status, this.formData).finally(()=>{
              this.loading = false;
            });
          } else {
            await businessApi.applyApprove(status, this.formData).finally(()=>{
              this.loading = false;
            });
          }
          this.$message.success('提交成功');
          this.$router.back();
        } catch (error) {
          this.loading = false;
          console.log(error);
        }
      }
      this.$store.commit('count/getCount');
    },
    async correction() {
      if (this.bussType == 5 || this.bussType == 6) {
        await this.$refs.CompanySteps3.save(1);
        this.$router.back();
      } else {
        await this.$refs.PersonalSteps3.save(1);
        this.$router.back();
      }
      this.$store.commit('count/getCount');
    },
    handleLoading(status) {
      this.loading = status;
    },
    needDecryptPhone(res) {
      return res && res.serviceType && res.serviceType=='2' && res.createBy && (this.bussType === 'b' || this.bussType === 'c' || this.bussType === 'd');
    },
  },
};
</script>
<style lang="scss" scoped>
.global-container {
  display: flex;
  flex-direction: column;
  .main {
    flex: 1;
  }
  .footer {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    .btn {
      margin-left: 24px;
      width: 120px;
    }
  }
}
</style>
